/*
 * Copyright 2012 Gregor Schauer
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package at.schauer.gregor.vienna.serializer.plugin;

import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @author Gregor Schauer
 */
public abstract class AbstractPhasePlugin<T> implements SerializerPlugin<T> {
	public enum Phase {
		preConstruct, postConstruct, postInitialize, preDeconstruct, postDeconstruct, postFinalize
	}

	public Set<Phase> phases = new HashSet<Phase>();

	public AbstractPhasePlugin(Phase... phases) {
		Collections.addAll(this.phases, phases);
	}

	protected abstract <E extends T> Map<String, Object> process(Map<String, Object> map, Class<E> clazz);

	protected abstract <E extends T> E process(E obj, Map<String, Object> map);

	@Override
	public Map<String, Object> preConstruct(Map<String, Object> map, Class<? extends T> clazz) {
		return phases.contains(Phase.preConstruct) ? process(map, clazz) : map;
	}

	@Override
	public <E extends T> E postConstruct(Map<String, Object> map, E obj) {
		return phases.contains(Phase.postConstruct) ? process(obj, map) : obj;
	}

	@Override
	public <E extends T> E postInitialize(Map<String, Object> map, E obj) {
		return phases.contains(Phase.postInitialize) ? process(obj, map) : obj;
	}

	@Override
	@SuppressWarnings("unchecked")
	public Map<String, Object> preDeconstruct(Map<String, Object> map, T obj) {
		return phases.contains(Phase.preDeconstruct) ? process(map, (Class<? extends T>) obj.getClass()) : map;
	}

	@Override
	@SuppressWarnings("unchecked")
	public Map<String, Object> postDeconstruct(Map<String, Object> map, T obj) {
		return phases.contains(Phase.postDeconstruct) ? process(map, (Class<? extends T>) obj.getClass()) : map;
	}

	@Override
	@SuppressWarnings("unchecked")
	public Map<String, Object> postFinalize(Map<String, Object> map, T obj) {
		return phases.contains(Phase.postFinalize) ? process(map, (Class<? extends T>) obj.getClass()) : map;
	}

	public Set<Phase> getPhases() {
		return phases;
	}

	public void setPhases(Set<Phase> phases) {
		this.phases = phases;
	}
}
